package router

import (
	"git.oschina.net/goweb/controller"
	"html/template"
	"log"
	"net/http"
	"reflect"
	"strings"
)

func LoginHandler(w http.ResponseWriter, r *http.Request) {
	pathInfo := strings.Trim(r.URL.Path, " ")
	parts := strings.Split(pathInfo, "/")

	var action = ""
	if len(parts) > 1 {
		action = strings.Title(parts[1]) + "Action"
	}

	controller := &controller.LoginController{}
	refValue := reflect.ValueOf(controller)
	method := refValue.MethodByName(action)

	if !method.IsValid() {
		method = refValue.MethodByName("LoginAction")
	}

	responseVal := reflect.ValueOf(w)
	requestVal := reflect.ValueOf(r)
	log.Println(responseVal, requestVal)
	method.Call([]reflect.Value{responseVal, requestVal})
}

func AjaxHandler(w http.ResponseWriter, r *http.Request) {
	path := strings.Trim(r.URL.Path, " ")
	parts := strings.Split(path, "/")

	var action = ""
	if len(parts) > 1 {
		action = strings.Title(parts[1]) + "Action"
	}

	ajxCtrl := &controller.AjaxController{}
	val := reflect.ValueOf(ajxCtrl)
	method := val.MethodByName(action)
	if !method.IsValid() {
		method = val.MethodByName("LoginAction")
	}

	responseVal := reflect.ValueOf(w)
	requestVal := reflect.ValueOf(r)
	method.Call([]reflect.Value{responseVal, requestVal})
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("admin_name")
	if err != nil || strings.TrimSpace(cookie.Value) == "" {
		http.Redirect(w, r, "/login", http.StatusFound)
	}

	path := strings.Trim(r.URL.Path, " ")
	parts := strings.Split(path, "/")

	action := ""
	if len(parts) > 1 {
		action = strings.Title(parts[1]) + "Action"
	}

	ctrl := &controller.IndexController{}
	val := reflect.ValueOf(ctrl)
	method := val.MethodByName(action)
	if !method.IsValid() {
		method = val.MethodByName("LoginAction")
	}

	response := reflect.ValueOf(w)
	request := reflect.ValueOf(r)
	userValue := reflect.ValueOf(cookie.Value)
	method.Call([]reflect.Value{response, request, userValue})
}

func NotFoundHandler(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path == "/" {
		http.Redirect(w, r, "/login", http.StatusFound)
	}

	t, err := template.ParseFiles("template/views/404.html")
	if err != nil {
		log.Println(err)
	}
	t.Execute(w, nil)
}
